#include "pch.h"
#include "ProjectView.h"
#include "ResourceManager.h"
#include "RendererEngine.h"

namespace mini
{
	CProjectView::CProjectView()
	{	
	}


	CProjectView::~CProjectView()
	{
	}

	void CProjectView::commitToGpu(DeviceContext* pDeviceContext)
	{
		auto pCamera = CRendererEngine::getSinglePtr()->getCamera();
		int nPassCount = mpMaterialUnit->getShaderUnitSize();
		for (int i = 0; i < nPassCount; ++i)
		{
			CShaderUnit* pShaderUnit = mpMaterialUnit->getShaderUnit(i);
			pShaderUnit->setViewMatrix(&pCamera->getViewMatrix());
			pShaderUnit->setProjectMatrix(&pCamera->getProjectMatrix());
			pShaderUnit->updateVSConstBuffer(1, &mMatrices);
		}
		CEffect::commitToGpu(pDeviceContext);
	}

	void CProjectView::setViewPoint(const CPoint3F& pt)
	{
		m_viewPt = pt;
		CVector up;
		// Setup the vector that points upwards.
		up.x = 0.0f;
		up.y = 1.0f;
		up.z = 0.0f;

		// Create the view matrix from the three vectors.
		D3DXMatrixLookAtLH(&mViewMatrix, &CVector(&m_viewPt.x), &CVector(&m_lookAtPt.x), &up);
		D3DXMatrixTranspose(&mMatrices[0], &mViewMatrix);
	}

	void CProjectView::setLookAt(const CPoint3F& pt)
	{
		m_lookAtPt = pt;
		CVector up;

		// Setup the vector that points upwards.
		up.x = 0.0f;
		up.y = 1.0f;
		up.z = 0.0f;

		// Create the view matrix from the three vectors.
		D3DXMatrixLookAtLH(&mViewMatrix, &CVector(&m_viewPt.x), &CVector(&m_lookAtPt.x), &up);
		D3DXMatrixTranspose(&mMatrices[0], &mViewMatrix);
	}

	void CProjectView::setProjectionParameters(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
	{
		m_fieldOfView = fieldOfView;
		m_aspectRatio = aspectRatio;
		m_nearPlane = nearPlane;
		m_farPlane = farPlane;
		D3DXMatrixPerspectiveFovLH(&mProjectMatrix, m_fieldOfView, m_aspectRatio, m_nearPlane, m_farPlane);
		D3DXMatrixTranspose(&mMatrices[1], &mProjectMatrix);
	}

	void CProjectView::setProjectTexture(const std::string& szTexture, int nSlot)
	{
	 	auto pTexture = dynamic_cast<CTexture*>(CResourceManager::getSinglePtr()->createResource(Texture));
		pTexture->setResourceName(szTexture);
		if (pTexture->initialise())
		{
			setProjectTexture(pTexture, nSlot);
			pTexture->setSampleState(mpMaterialUnit->getSampler(0));
		}
	}

	void CProjectView::setProjectTexture(CTexture* pTexture, int nSlot)
	{
		mpMaterialUnit->setTexture(pTexture, nSlot);
	}

	CMatrix& CProjectView::getViewMatrix()
	{
		return mViewMatrix;
	}

	CMatrix& CProjectView::getProjectMatrix()
	{
		return mProjectMatrix;
	}

}